const {Controller} = require('uni-cloud-router')
const createConfig = require('uni-config-center')
const uniPayConfig = createConfig({pluginId: 'uni-pay'})
const global = require("globalunit");
const uniPay = require("../uni-pay");
const path = require('path');
const config = {
	"appId": uniPayConfig.config("app.weixin.appid"), // app开放平台下的应用的appid
	"mchId": uniPayConfig.config("app.weixin.mchid"), // 商户id
	"v3Key": uniPayConfig.config("app.weixin.v3Key"), // v3的api key
	"appCertPath": path.join(__dirname, '../wxpay/apiclient_cert.pem'), // v3需要用到的证书
	"appPrivateKeyPath": path.join(__dirname, '../wxpay/apiclient_key.pem'), // v3需要用到的证书
	// 如果你的商户验签模式是微信支付公钥形式，则需要再填写以下2个参数
	// "wxpayPublicKeyPath": path.join(__dirname, '../wxpay/pub_key.pem'), // 微信支付公钥的正式文件地址
	// "wxpayPublicKeyId": "", // 微信支付公钥的id
};
const unipayIns = uniPay.initWeixinV3({
	...config
});
module.exports = class MineController extends Controller {
	// 获取用户信息
	async getmyinfo() {
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}
		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0) {
			return {
				errcode: 10005,
			};
		}
		return {
			errcode: 0,
			data: {
				user: await user.toparam()
			}
		};
	}
	// 邀请好友
	async getyaoqing() {
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}
		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0) {
			return {
				errcode: 10005,
			};
		}
		// var team1 = await this.ctx.uniID.getInvitedUser({
		// 	uid: this.ctx.data.uid,
		// 	level: 1,
		// 	limit: 1,
		// 	offset: 0,
		// 	needTotal: true
		// })
		// var team2 = await this.ctx.uniID.getInvitedUser({
		// 	uid: this.ctx.data.uid,
		// 	level: 2,
		// 	limit: 1,
		// 	offset: 0,
		// 	needTotal: true
		// })
		return {
			errcode: 0,
			data: {
				user: await user.toparam(),
				total1: user.zhituifriend,
				total2: user.kuosanfriend
			}
		};
	}

	//身份验证
	async authentication() {
		if (!this.ctx.data.uid || !this.ctx.data.idcard || !this.ctx.data.realname) {
			return {
				errcode: 10001,
			};
		}

		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0) {
			return {
				errcode: 10005,
			};
		}

		// if (user.idcard != '') {
		// 	return {
		// 		errcode: 30001,
		// 	};
		// }

		// if (user.realname != '') {
		// 	return {
		// 		errcode: 30001,
		// 	};
		// }

		user.idcard = this.ctx.data.idcard;
		user.realname = this.ctx.data.realname;
		if(user.isauthentication != 1){
			user.isauthentication = 1;
			await user.save()
			if(user.shangji != 0){
				var sjuser = await global.UserLogic.loaduser(this._db, user.shangji);
				sjuser.zhituifriend += 1
				await sjuser.save()
				if(sjuser.shangji != 0){
					var ssjuser = await global.UserLogic.loaduser(this._db, sjuser.shangji);
					ssjuser.kuosanfriend += 1
					await ssjuser.save()
				}
				user.isadd = 1;
			}
			await global.FriendActiveLogic.addcount(this._db, this.ctx.data.uid, "friendcount");
		}
		user.isauthentication = 1;
		await user.save()
		await user.load()
		
		return {
			errcode: 0,
			data: {
				user: await user.toparam()
			}
		};
	}
	
	//微信提现
	async withdraw() {
		if (!this.ctx.data.uid || !this.ctx.data.amount) {
			return {
				errcode: 10001,
			};
		}

		var amount = parseFloat(this.ctx.data.amount);
		if (amount != 0.3 && amount != 20 && amount != 50 && amount != 100 && amount != 500 && amount != 1000) {
			return {
				errcode: 10028,
			};
		}

		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0 || user._id != this.ctx.data.uid) {
			return {
				errcode: 10005,
			};
		}
        
		if (user.realname == '') {
			return {
				errcode: 10018,
			};
		}

		// 判断是不是首次提现   首次不收手续费
		var commissionbili = 0;
		if (user.isfirstwithdraw == 0) {
			// 第二次提现开始收取手续费，获取手续费比例
			commissionbili = await global.config.get("withdraw", "commission") / 100;
		}
		// 手续费金额
		var commission = Math.floor(amount * commissionbili * 100) / 100;
		// 实际提现金额 = 提现金额 - 手续费
		var realamount = amount - commission;
		console.log('realamount: ',realamount);
		var fangda = await global.config.get("fangda");
		// fangda 等于1000，是因为系统内部用“毫”为金额单位，能避免小数精度问题，也能处理比“分”更小的金额。
		// 用户钱包余额user.fen单位是“毫”（即1元=1000毫），和，amount要提现的金额单位是元*1000转成‘毫’，比较
		if (user.fen < amount * fangda) {
			return {
				errcode: 10012,
			};
		}
		// 获取提现方式
		var tixiantype = await global.config.get('tixiantype','type')
		// 支付宝
		if(tixiantype == 'zhifubao'){
			if(user.zhifubao == ''){
				return {
					errcode: 10052,
				};
			}
			// 判断是否已经申请提现
			const res = await this.db.collection('withdrawrecord_log').where({
				uid: this.ctx.data.uid,
				status: 0,
			}).get();
			if (res.data && res.data.length > 0) {
				return {
					errcode: 10011,
				};
			}
			await user.xiafen(amount);
			if (user.isfirstwithdraw == 1) {
				user.isfirstwithdraw = 0;
			}
			await user.save();
			await user.load();
			var up = await user.toparam();
			// 提交申请
			var msg = {
				"uid": this.ctx.data.uid,
				"realamount":realamount,//扣除手续费后的实际到账金额
				"count": amount,
				"commission": commission,
				"balance": up["fen"],
				"status": 0,
				"msg":"",
				"type":"zhifubao",
				"createtime": Math.floor(Date.now() / 1000),
			};
			await global.QueueHelper.putLog(this.db, "withdrawrecord_log", msg);
		}else{
			if(user.openid == ''){
				return {
					errcode: 10053,
				};
			}
			// 所有提现方式都需要审核
			// 判断是否已经申请提现
			const res = await this.db.collection('withdrawrecord_log').where({
				uid: this.ctx.data.uid,
				status: 0,
			}).get();
		
			if (res.data && res.data.length > 0) {
				return {
					errcode: 10011,
				};
			}
		
			await user.xiafen(amount);
			// isfirstwithdraw为1时是首次提现，为0时不是首次提现
			// if (user.isfirstwithdraw == 1) {
			// 	user.isfirstwithdraw = 0;
			// }
			await user.save();
			await user.load();
			var up = await user.toparam();
			
			// 生成订单号
			let date = Date.now();
			let rund = Math.ceil(date / 1000);
			let outTradeNo = rund + '' + user.inviteCode;
			console.log(' ceshi jin lai  99999--outTradeNo--->' + outTradeNo)
			
			// 提交申请
			var msg = {
				"uid": this.ctx.data.uid,
				"realamount":realamount,//扣除手续费后的实际到账金额
				"count": amount,//提现金额
				"commission": commission,//扣除手续费
				"balance": up["fen"],//余额
				"status": 0,//提现状态，需要审核
				"msg": "",//驳回原因
				"type": "weixin",//提现方式
				"outTradeNo":outTradeNo,// 商户系统内部的商家单号
				"createtime": Math.floor(Date.now() / 1000),
			};
			await global.QueueHelper.putLog(this.db, "withdrawrecord_log", msg);
			// 余额明细记录
			await global.QueueHelper.profitrecord(this.db, user._id, amount, up['fen'], '提现审核中', outTradeNo);
			// await global.QueueHelper.putLog(this.db, "user_login",up);
			
			// if (amount != 0.3) {
			// 	// 判断是否已经申请提现
			// 	const res = await this.db.collection('withdrawrecord_log').where({
			// 		uid: this.ctx.data.uid,
			// 		status: 0,
			// 	}).get();
			
			// 	if (res.data && res.data.length > 0) {
			// 		return {
			// 			errcode: 10011,
			// 		};
			// 	}
			
			// 	await user.xiafen(amount);
			// 	if (user.isfirstwithdraw == 1) {
			// 		user.isfirstwithdraw = 0;
			// 	}
			// 	await user.save();
			// 	await user.load();
			// 	var up = await user.toparam();
			
			// 	// await global.QueueHelper.putLog(this.db, "user_login",up);
			// 	// 提交申请
			// 	var msg = {
			// 		"uid": this.ctx.data.uid,
			// 		"count": amount,
			// 		"commission": commission,
			// 		"balance": up["fen"],
			// 		"status": 0,
			// 			"msg":"",
			// 			"type":"weixin",
			// 		"createtime": Math.floor(Date.now() / 1000),
			// 	};
			
			// 	await global.QueueHelper.putLog(this.db, "withdrawrecord_log", msg);
			// } else {
			// 	// TODO : 微信提现接口  返回成功之后  扣用户fen
			// 	// 通过code获取openid
			// 	if (user.isfirstwithdraw == 0) {
			// 		return {
			// 			errcode: 10042,
			// 		};
			// 	}
			
			// 	if (user.realname == '') {
			// 		return {
			// 			errcode: 10018,
			// 		};
			// 	}
			// 	const config = {
			// 		appid:uniPayConfig.config('app.weixin.appid') , //公众号id
			// 		mchid:uniPayConfig.config('app.weixin.mchid') , //商户id
			// 		partnerKey: uniPayConfig.config('app.weixin.partnerKey'), //安全密钥
			// 		pfx: wxpay.fs.readFileSync(wxpay.path.resolve(__dirname, "apiclient_cert.p12")),
			// 		notify_url:"",
			// 		spbill_create_ip: 'IP地址'
			// 	};
				
			// 	// const api = new tenpay(config);
			// 	// 调试模式(传入第二个参数为true, 可在控制台输出数据)
			// 	const api = new wxpay.tenpay(config, true);
			
			// 	let date = Date.now();
			// 	let rund = Math.ceil(date / 1000);
			// 	let partner = rund + '' + user.inviteCode;
			// 	console.log(' ceshi jin lai  99999--partner--->' + partner)
			// 	let result = await api.transfers({
			// 		partner_trade_no: partner, //订单号
			// 		openid: user.openid,
			// 		re_user_name: user.realname, //真实姓名
			// 		amount: Math.round(amount*100),
			// 		desc: '企业付款描述信息'
			// 	});
			// 	console.log(' ceshi jin lai  88888----->')
			// 	console.log(result)
			
			// 	if (result['return_code'] == 'SUCCESS' && result['result_code'] == 'SUCCESS') {
			// 		await user.xiafen(realamount);
			// 		if (user.isfirstwithdraw == 1) {
			// 			user.isfirstwithdraw = 0;
			// 		}
			// 		await user.save();
			// 		await user.load();
			// 		var up = await user.toparam();
			// 		// await global.QueueHelper.putLog(this.db, "user_login",up);
			
			// 		await global.QueueHelper.profitrecord(this.db, user._id, 0.3, up['fen'], '提现成功', 11);
			// 		var msg = {
			// 			"uid": this.ctx.data.uid,
			// 			"count": amount,
			// 			"commission": commission,
			// 			"balance": up["fen"],
			// 			"status": 1,
			// 				 "msg":"",
			// 				 "type":"weixin",
			// 			"createtime": Math.floor(Date.now() / 1000),
			// 		};
					
			// 		await global.QueueHelper.putLog(this.db, "withdrawrecord_log", msg);
			// 	} else {
			// 		return {
			// 			errcode: 10042,
			// 		};
			// 	}
			// }
		}
		
		return {
			'errcode': 0,
			"data": {
				"user": await user.toparam(),
				"amount": amount,
				"commission": commission
			}
		};
	}
	
	// 检查提现状态，是否有待确认收款
	// 	/*
	// 		提现状态status：
	// 		0: '审核中',
	// 		1: '审批通过，提现待确认',
	// 		2: '审批拒绝',
	// 		3: '打款已完成'
	// 		4: '失败'
	// 	*/
	async checkWithdraw(){
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}
			
		var user = await global.UserLogic.loaduser(this.db, this.ctx.data.uid);
		if (user._id == 0) {
			return {
				errcode: 10005,
			};
		}
			
		if (user.accountstatus == 1 || user.accountstatus == "1") {
			return {
				errcode: 10008,
			};
		}
		
		// 判断提现类型
		var tixiantype = await global.config.get('tixiantype', 'type')
		if (tixiantype == 'zhifubao') {
			// 支付宝提现
			return {
				errcode: 10001,
			};
		}
		
		const withdrawRes = await this.db.collection('withdrawrecord_log').where({
			uid: this.ctx.data.uid,
			status:1,
			type:"weixin"
		}).get()
		console.log('withdrawRes: ',withdrawRes);
		
		// 判断更新是否有待确认提现
		if (withdrawRes.data.length) {
			return{
				errCode: 0,
				errMsg: '有待确认的提现',
			}
		}else{
			return {
				errCode: 'NO_DATA',
				errMsg: '没有待确认的提现'
			}
		}
	}
	// 提现申请通过了，开始微信转账
	async wxTransfer(){
		
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}
			
		var user = await global.UserLogic.loaduser(this.db, this.ctx.data.uid);
		if (user._id == 0) {
			return {
				errcode: 10005,
			};
		}
			
		if (user.accountstatus == 1 || user.accountstatus == "1") {
			return {
				errcode: 10008,
			};
		}
		
		if (user.openid == '') {
			return {
				errcode: 10053,
			};
		}
		const outTradeNo = this.ctx.data.outTradeNo;
		console.log(' ceshi jin lai  99999--outTradeNo--->' + outTradeNo)
		if (!outTradeNo) {
			return {
				errcode: 10001
			};
		}
		
		const withdrawRecord = await this.db.collection('withdrawrecord_log').where({
			uid: this.ctx.data.uid,
			outTradeNo: outTradeNo,
		}).get();
		const withdrawData = withdrawRecord.data[0];
		console.log('withdrawData: ',withdrawData);
		
		if(withdrawData.status != 1){
			return {
				errcode: 10001
			};
		}
		let realamountEnd = 0;
		if(withdrawData && withdrawData.realamount){
			// 转账金额单位为“分，元转成分
			realamountEnd = Math.round(withdrawData.realamount * 100);
			console.log('realamountEnd: ',realamountEnd);
		}
		
		let transferRes = await unipayIns.request({
			method: "POST",
			useEipProxy: false, // 阿里云空间需要设置为true
			url: "/v3/fund-app/mch-transfer/transfer-bills",
			data: {
				// 用户在商户appid下的唯一标识。发起转账前需获取到用户的OpenID，
				appid: config.appId,
				// 商户系统内部的商家单号
				out_bill_no: outTradeNo,
				openid:user.openid,
				// 转账金额单位为“分
				transfer_amount: realamountEnd,
				// 转账备注，用户收款时可见该备注信息
				transfer_remark: "转账",
				// 该笔转账使用的转账场景，可前往“商户平台-产品中心-商家转账”中申请。如：1000（现金营销），1006（企业报销）等
				transfer_scene_id: "1000",
				user_recv_perception: "现金奖励",
				transfer_scene_report_infos: [{
						info_type: "活动名称",
						info_content: "新会员有礼"
					},
					{
						info_type: "奖励说明",
						info_content: "注册会员抽奖一等奖"
					}
				],
				// 收款方真实姓名
				// user_name: user.realname
			}
		});
		console.log('transferRes: ',transferRes);
		
		if (!transferRes.packageInfo) {
			return {
				errCode: -1,
				errMsg: "请求异常，请重试"
			}
		}
		
		if (typeof transferRes.errCode !== "number") {
			transferRes.errCode = -1;
		}
		const options = {
			mchId: config.mchId,
			appId: config.appId,
			package: transferRes.packageInfo,
			openId: user.openid
		};
		
		const withdrawUpdate = await this.db.collection('withdrawrecord_log').where({
			uid: this.ctx.data.uid,
			status: 1,
			outTradeNo,
		}).update({
			status: 3,// 打款状态，直接改成已完成
			options,
			transferBillNo: transferRes.transferBillNo ,// 微信转账单号
			transferCreateTime: transferRes.createTime // 微信转账创建时间
		})
		console.log('withdrawUpdate: ',withdrawUpdate);
		// 3打款完成 4失败
		const statusUpdate = withdrawUpdate.updated > 0 ? 3 : 4
		console.log('statusUpdate',statusUpdate)
		
		// 更新收益记录
		let profitrecordRes = await this.db.collection('user_profitrecord').where({
			uid: this.ctx.data.uid,
			t: withdrawData.outTradeNo,
		}).update({
			explane:'提现成功'
		});
		console.log('profitrecordRes: ',profitrecordRes);
		
		// await user.save();
		// await user.load();
		
		return {
			errcode: 0,
		  wxState: transferRes.state,
			outTradeNo,
		  options,
			status:statusUpdate
		};
		
	}
	
	// 测试回调
	async ceshihuidiao() {
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}

		console.log('ce shi  hui diao  打快成功？ --->')
		return {
			errcode: 0,
		};
	}
	// 获取提现记录
	async getwithdrawrecord() {
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}
		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0 || user._id != this.ctx.data.uid) {
			return {
				errcode: 10005,
			};
		}
		var limit = this.ctx.data.limit || 20;
		var res = await this.db.collection('withdrawrecord_log').where({
			uid: this.ctx.data.uid,
		}).limit(limit).get();

		var count = await this.db.collection('withdrawrecord_log').where({
			uid: this.ctx.data.uid,
		}).count();

		return {
			'errcode': 0,
			"data": {
				"record": res.data,
				'totalcount': count,
			}
		};
	}
	// 获取收益记录
	async getprofitrecord() {
		if (!this.ctx.data.uid) {
			return {
				errcode: 10001,
			};
		}
		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0 || user._id != this.ctx.data.uid) {
			return {
				errcode: 10005,
			};
		}

		var limit = this.ctx.data.limit || 20;
		var res = await this.db.collection('user_profitrecord').where({
			uid: this.ctx.data.uid,
		}).limit(limit).get();

		var count = await this.db.collection('user_profitrecord').where({
			uid: this.ctx.data.uid,
		}).count();

		return {
			'errcode': 0,
			"data": {
				"record": res.data,
				'totalcount': count,
			}
		};
	}
	// 激励视频回调
	async videoCallBack() {
		if (!this.ctx.data.uid || !this.ctx.data.reward_amount || !this.ctx.data.reward_name) {
			return {
				errcode: 10001,
			};
		}
		var user = await global.UserLogic.loaduser(this._db, this.ctx.data.uid);
		if (user._id == 0 || user._id != this.ctx.data.uid) {
			return {
				errcode: 10005,
			};
		}
		var quancount = await global.RouletteLogic.getquancount(this.db, this.ctx.data.uid);
		if (quancount <= 0) {
			return {
				errcode: 10038,
			};
		}
		var res = await this.db.collection('lastvideotimes').doc(this.ctx.data.uid).update({
			time: Math.floor(Date.now() / 1000)
		})
		if (res.updated != 1) {
			await this.db.collection('lastvideotimes').doc(this.ctx.data.uid).set({
				time: Math.floor(Date.now() / 1000)
			})
		}
		// 减视频次数
		await global.RouletteLogic.addquan(this.db, this.ctx.data.uid);
		var reward_name = this.ctx.data.reward_name
		var coin = "0"
		if (reward_name == "抽奖次数") {
			await global.RouletteLogic.clearcount(this.db, this.ctx.data.uid);
		} else if (reward_name == "金币") {
			// var time = await global.config.get("globalinfo", "videocoin");
			// var grow = await global.Decimal.multipliedBy(user.persec, time);
			// var c = await global.Decimal.add(grow, 0);
			// coin = c
			// await user.shangcoin(c,false,"视频收益")
			// await user.save()
			// await user.load()
			
			var lvl = user.maxlvl
			if(lvl<1){
				lvl = 1
			}
			if(lvl>37){
				lvl = 37
			}
			// var grow = await global.config.get("cats","cat"+lvl,"price");
			// var c = await global.Decimal.add(grow, 0);
			
			
			var catinfo = await global.CatLogic.loadcat(this.db, this.ctx.data.uid);
			console.log("CatLogic.loadcat end");
			// console.log(catinfo)
			var num = catinfo['cat'+lvl];
			var jie = 1;
			if(!num){
				jie = 1;
			}else{
				jie = num+1;
			}
			// 计算购买价格
			var price = await global.CatLogic.calprice(lvl, jie);
			console.log("calprice:", price);
			
			coin = price+""
			await user.shangcoin(price+"",false,"视频收益")
			await user.save()
			await user.load()
		} else if (reward_name == "5倍奖励") {
			await global.RouletteLogic.setrolltimes(this.db, this.ctx.data.uid, 5);
		} else if (reward_name == "10倍奖励") {
			await global.RouletteLogic.setrolltimes(this.db, this.ctx.data.uid, 10);
		} else if (reward_name == "离线收益") {
			var offlinedata = await this.db.collection('offlinebonus').doc(this.ctx.data.uid).get();
			if (offlinedata.data.length > 0) {
				var offlinebonus = parseInt(offlinedata.data[0]['offlinebonus']) * 2
				await this.db.collection('offlinebonus').doc(this.ctx.data.uid).update({
					offlinebonus: offlinebonus
				});
				coin = offlinebonus+''
			}
		}

		if (user.isauthentication == 1) {
			await global.FriendActiveLogic.addcount(this.db, this.ctx.data.uid, "videocount");
		}
		await global.BideLogic.addcount(this.db, this.ctx.data.uid, 'videocount', 1);

		// var task = await global.DialytaskLogic.loadtask(this.db, this.ctx.data.uid);
		// await task.shangtodaydata('todayvideocount');
		// await task.save()
		user.videocount = user.videocount + 1;
		await user.save()
		await user.load()
		await global.QueueHelper.putLog(this.db, "user_login", await user.toparam());
		return {
			errcode: 0,
			data: {
				user: await user.toparam(),
				reward_name:reward_name,
				coin:coin
			},
		};
	}
}
